﻿using AspNet.Identity.Dapper.Db;
using Dapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace AspNet.Identity.Dapper
{
    public class UserClaimsTable
    {
        private readonly DbManager _db;

        public UserClaimsTable(DbManager dbManager)
        {
            this._db = dbManager;
        }

        public ClaimsIdentity FindByUserId(Guid userId)
        {
            ClaimsIdentity claims = new ClaimsIdentity();

            foreach (var c in _db.Connection.Query("Select * from UserClaim where UserId=@userId", new { userId=userId.ToString() }))
            {
                claims.AddClaim(new Claim(c.ClaimType, c.ClaimValue));
            }

            return claims;
        }

        /// <summary>
        /// Deletes all claims from a user given a userId
        /// </summary>
        /// <param name="userId">The user's id</param>
        /// <returns></returns>
        public bool  Delete(Guid userId)
        {
            return _db.Connection.Execute(@"Delete from UserClaim where UserId = @userId", new { userId=userId.ToString() })>0;
        }

        /// <summary>
        /// Inserts a new claim in UserClaims table
        /// </summary>
        /// <param name="MemberClaim">User's claim to be added</param>
        /// <param name="userId">User's id</param>
        /// <returns></returns>
        public bool Insert(Claim userClaim, Guid userId)
        {
            return _db.Connection.Execute(@"Insert into UserClaim (ClaimValue, ClaimType, MemberId) 
                values (@value, @type, @userId)",
                    new
                    {
                        value = userClaim.Value,
                        type = userClaim.Type,
                        userId=userId.ToString()
                    })>0;
        }

        /// <summary>
        /// Deletes a claim from a user 
        /// </summary>
        /// <param name="user">The user to have a claim deleted</param>
        /// <param name="claim">A claim to be deleted from user</param>
        /// <returns></returns>
        public bool Delete(IdentityUser user, Claim claim)
        {
            return _db.Connection.Execute(@"Delete from UserClaim 
            where UserId = @userId and @ClaimValue = @value and ClaimType = @type",
                new
                {
                    userId = user.Id.ToString(),
                    ClaimValue = claim.Value,
                    type = claim.Type
                })>0;
        }
    }
}
